<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="退货单编号" prop="sn">
        <el-input
          v-model="queryParams.sn"
          placeholder="请输入退货单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['xiaoshou:refund:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['xiaoshou:refund:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['xiaoshou:refund:remove']"
        >删除</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['xiaoshou:refund:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="refundList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="主键" align="center" prop="id" />-->
      <el-table-column label="退货单编号" align="center" prop="sn" />
<!--      <el-table-column label="要退货的订单id" align="center" prop="orderId" />-->
      <el-table-column label="关联订单" align="center" prop="orderSn" />
<!--      <el-table-column label="要退货的订单类型" align="center" prop="orderType" />-->
<!--      <el-table-column label="部门id" align="center" prop="deptId" />-->
<!--      <el-table-column label="仓库id" align="center" prop="warehouseId" />-->
      <el-table-column label="退货时间" align="center" prop="returnTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.returnTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属部门" align="center" prop="deptName" />
      <el-table-column label="仓库" align="center" prop="warehouseName" />

<!--      <el-table-column label="经手人id" align="center" prop="handleById" />-->
<!--      <el-table-column label="销售经理" align="center" prop="distributionName" />-->
      <el-table-column label="经手人" align="center" prop="handleByName" />
      <el-table-column label="状态" align="center" prop="status" />

<!--      <el-table-column label="审核人id" align="center" prop="auditById" />-->
<!--      <el-table-column label="审核人" align="center" prop="auditBy" />-->
<!--      <el-table-column label="审核备注" align="center" prop="auditRemark" />-->
<!--      <el-table-column label="退货说明" align="center" prop="returnRemark" />-->
<!--      <el-table-column label="创建者" align="center" prop="creator" />-->
<!--      <el-table-column label="更新者" align="center" prop="updater" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status === '未提交' || scope.row.status === '已驳回'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['xiaoshou:refund:edit']"
          >编辑</el-button>

          <el-button
            v-if="scope.row.status === '未提交' || scope.row.status === '已驳回'"
            size="mini"
            type="text"
            icon="el-icon-upload"
            @click="handleSubmit(scope.row)"
            v-hasPermi="['xiaoshou:refund:edit']"
          >提交</el-button>

          <el-button
            v-if="scope.row.status === '待审核'"
            size="mini"
            type="text"
            icon="el-icon-refresh-left"
            @click="handleWithdraw(scope.row)"
            v-hasPermi="['xiaoshou:refund:edit']"
          >撤回</el-button>

          <el-button
            v-if="scope.row.status === '待审核'"
            size="mini"
            type="text"
            icon="el-icon-finished"
            @click="handleAudit(scope.row)"
            v-hasPermi="['xiaoshou:refund:audit']"
          >审核</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单退货对话框 -->

    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
<!--        <el-form-item label="退货单编号" prop="sn">-->
<!--          <el-input v-model="form.sn" placeholder="请输入退货单编号" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="要退货的订单id" prop="orderId">-->
<!--          <el-input v-model="form.orderId" placeholder="请输入要退货的订单id" />-->
<!--        </el-form-item>-->
        <el-form-item label="退货时间" prop="returnTime">
          <el-date-picker clearable
                          v-model="form.returnTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择退货时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="所属部门" prop="deptName">
          <el-input v-model="form.deptName" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="仓库" prop="warehouseName">
          <el-input v-model="form.warehouseName" placeholder="请输入仓库名称" />
        </el-form-item>

        <el-form-item label="销售订单">
          <el-button
            type="primary"
            @click="openOrderDialog"
          >选择订单</el-button>
          <span v-if="form.orderSn" style="margin-left: 10px;">
          已选：{{ form.orderSn }}
        </span>
        </el-form-item>

        <el-dialog title="退货单审核" :visible.sync="auditDialogVisible" width="500px" append-to-body>
          <el-form ref="auditForm" :model="auditForm" :rules="auditRules" label-width="80px">
            <el-form-item label="退货时间" prop="returnTime">
              {{ formatTime(auditForm.returnTime) }}
            </el-form-item>
            <el-form-item label="所属部门" prop="deptName">
              {{ auditForm.deptName }}
            </el-form-item>
            <el-form-item label="零售订单" prop="orderSn">
              {{ auditForm.orderSn }}
            </el-form-item>
            <el-form-item label="经手人" prop="handleByName">
              {{ auditForm.handleByName }}
            </el-form-item>
            <el-form-item label="退货说明" prop="returnRemark">
              {{ auditForm.returnRemark }}
            </el-form-item>
            <el-form-item label="审核结果" prop="status">
              <el-radio-group v-model="auditForm.status">
                <el-radio label="通过">通过</el-radio>
                <el-radio label="驳回">驳回</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="审核备注" prop="auditRemark">
              <el-input v-model="auditForm.auditRemark" type="textarea" placeholder="请输入审核备注"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="auditDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitAudit">确定</el-button>
          </div>
        </el-dialog>


        <el-dialog title="选择销售订单" :visible.sync="orderDialogVisible" width="70%">
          <el-table
            v-loading="orderLoading"
            :data="orderList"
            @selection-change="handleOrderSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="订单编号" prop="sn" align="center" />
            <el-table-column label="客户名称" prop="ownerName" align="center" />
            <el-table-column label="下单时间" prop="orderTime" align="center" :formatter="formatTime" />
          </el-table>
          <div slot="footer" class="dialog-footer">
            <el-button @click="orderDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmOrderSelection">确定</el-button>
          </div>
        </el-dialog>


        <el-form-item label="经手人名称" prop="handleByName">
          <el-input v-model="form.handleByName" placeholder="请输入经手人名称" />
        </el-form-item>

        <el-form-item label="退货说明" prop="returnRemark">
          <el-input v-model="form.returnRemark" placeholder="请输入退货说明" />
        </el-form-item>
        <el-divider>订单商品明细</el-divider>
        <el-table
          v-loading="goodsLoading"
          :data="orderGoodsList"
          border
          style="margin-top: 20px;"
        >
          <el-table-column prop="sn" label="商品编号" width="150"></el-table-column>
          <el-table-column prop="name" label="商品名称" width="150"></el-table-column>
<!--          <el-table-column prop="spec" label="规格"></el-table-column>-->
          <el-table-column prop="num" label="数量" width="150" align="center"></el-table-column>
          <el-table-column prop="price" label="单价" width="150" align="center"></el-table-column>
          <el-table-column prop="amount" label="金额" width="160" align="center">
            <template slot-scope="scope">
              ¥{{ scope.row.amount.toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>

        <div slot="footer" class="dialog-footer">
          <el-button @click="orderDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmOrderSelection">确定</el-button>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRefund, getRefund, delRefund, addRefund, updateRefund,listOrder,getOrderInfo } from "@/api/xiaoshou/refund";
import {getOrderGoods} from "../../../api/xiaoshou/refund";
import { listGoods } from "@/api/goods/goods";

export default {
  name: "Refund",
  data() {
    return {
      goodsLoading: false, // 商品加载状态
      orderGoodsList: [], // 订单商品列表
      selectedGoods: [], // 选中的商品
      goodsList: [],
      goodsDialogVisible: false,
      auditDialogVisible: false,
      returnList: [], // 退货商品明细列表
      selectedOrder: null, // 当前选中的订单
      auditForm: {
        id: null,
        status: '',
        auditRemark: ''
      },
      auditRules: {
        status: [
          { required: true, message: '请选择审核结果', trigger: 'change' }
        ]
      },
      orderDialogVisible: false,    // 控制弹窗显示
      orderLoading: false,         // 加载状态
      orderList: [],               // 订单列表数据
      selectedOrders: [],
      // 遮罩层
      loading: true,
      supplierList: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单退货表格数据
      refundList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sn: null,
        orderId: null,
        orderSn: null,
        orderType: null,
        deptId: null,
        warehouseId: null,
        deptName: null,
        warehouseName: null,
        distributionName: null,
        handleById: null,
        handleByName: null,
        status: null,
        returnTime: null,
        auditById: null,
        auditBy: null,
        auditRemark: null,
        returnRemark: null,
        creator: null,
        updater: null,
        owner_name:null,
        order_time:null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleSubmit(row) {
      this.$modal.confirm('确认提交该退货单吗？').then(() => {
        const form = { ...row, status: '待审核' };
        updateRefund(form).then(response => {
          this.$modal.msgSuccess("提交成功");
          this.getList();
        });
      }).catch(() => {});
    },

    // 撤回退货单
    handleWithdraw(row) {
      this.$modal.confirm('确认撤回该退货单吗？').then(() => {
        const form = { ...row, status: '未提交' };
        updateRefund(form).then(response => {
          this.$modal.msgSuccess("撤回成功");
          this.getList();
        });
      }).catch(() => {});
    },

    // 打开审核对话框
    handleAudit(row) {
      this.auditForm = {
        id: row.id,
        status: '', // 初始为空，让用户选择
        auditRemark: '',
        returnTime: row.returnTime, // 添加这些字段用于显示
        deptName: row.deptName,
        orderSn: row.orderSn,
        handleByName: row.handleByName,
        returnRemark: row.returnRemark
      };
      this.auditDialogVisible = true;
    },

    // 提交审核
    submitAudit() {
      this.$refs["auditForm"].validate(valid => {
        if (valid) {
          console.log('提交审核数据:', this.auditForm); // 调试用

          const form = {
            id: this.auditForm.id,
            status: this.auditForm.status === '通过' ? '审核通过' : '未提交',
            auditRemark: this.auditForm.auditRemark,
            auditBy: this.$store.state.user.name, // 添加审核人
            auditTime: new Date() // 添加审核时间
          };

          updateRefund(form).then(response => {
            this.$modal.msgSuccess("审核完成");
            this.auditDialogVisible = false;
            this.getList();
          }).catch(error => {
            console.error('审核失败:', error); // 调试用
            this.$modal.msgError("审核失败");
          });
        }
      });
    },
    handleSelectGoods() {
      this.getGoodsList();
      this.goodsDialogVisible = true;
    },
    formatTime(row, column, cellValue) {
      return this.parseTime(cellValue, '{y}-{m}-{d}');
    },
    openOrderDialog() {
      this.orderDialogVisible = true;
      this.orderLoading = true;
      // 调用API获取订单列表
      listOrder({
        excludeIds: this.selectedOrderIds // 排除已选择的订单
      }).then(response => {
        this.orderList = response.rows;
        this.orderLoading = false;
      });
    },
    handleOrderSelectionChange(selection) {
      this.selectedOrders = selection;
      if (selection.length > 0) {
        this.getOrderGoods(selection[0].id); // 当选中订单时获取商品
      } else {
        this.orderGoodsList = []; // 未选中时清空商品列表
      }
    },
    confirmOrderSelection() {
      if (this.selectedOrders.length === 0) {
        this.$message.warning("请至少选择一条订单");
        return;
      }

      const selectedOrder = this.selectedOrders[0];

      // 获取订单信息
      getOrderInfo(selectedOrder.id).then(response => {
        if (response.code === 200) {
          // 填充表单数据
          this.form = {
            ...this.form,
            orderId: selectedOrder.id,
            orderSn: selectedOrder.sn,
            warehouseId: response.data.warehouseId,
            warehouseName: response.data.warehouseName,
            deptId: response.data.deptId,
            deptName: response.data.deptName,
            owner_name: selectedOrder.ownerName,
            order_time: selectedOrder.orderTime
          };

          // 获取商品明细
          this.getOrderGoods(selectedOrder.id);
          this.orderDialogVisible = false;
        } else {
          this.$message.error(response.msg || "获取订单信息失败");
        }
      }).catch(error => {
        console.error("获取订单信息失败:", error);
        this.$message.error("获取订单信息失败");
      });
    },

    getOrderGoods(orderId) {
      if (!orderId) {
        this.$message.error("订单ID无效");
        return;
      }

      this.goodsLoading = true;
      getOrderGoods(orderId).then(response => {
        console.log("商品明细响应数据:", response);
        if (response.code === 200 && response.data) {
          // 映射商品数据字段
          this.orderGoodsList = response.data.map(item => ({
            id: item.id,
            sn: item.sn || item.goodsSn || '',
            name: item.name || item.goodsName || '',
            spec: item.spec || item.specName || '',
            price: item.price || item.productPrice || 0,
            num: item.countNum || item.num || 1, // 默认设为1而不是0
            amount: (item.price || 0) * (item.countNum || item.num || 1) // 计算单件金额
          }));
        } else {
          this.$message.warning(response.msg || "该订单没有商品明细");
          this.orderGoodsList = [];
        }
        this.goodsLoading = false;
      }).catch(error => {
        console.error("获取商品明细失败:", error);
        this.$message.error("获取商品明细失败");
        this.goodsLoading = false;
      });
    },
    confirmGoodsSelection() {
      // 过滤出有退货数量的商品
      this.returnList = this.orderGoodsList.filter(item => item.returnNum > 0);
      this.goodsDialogVisible = false;
      this.$message.success(`已选择 ${this.returnList.length} 个退货商品`);
    },
    /** 查询订单退货列表 */
    getList() {
      this.loading = true;
      listRefund(this.queryParams).then(response => {
        this.refundList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sn: null,
        orderId: null,
        orderSn: null,
        orderType: null,
        deptId: null,
        warehouseId: null,
        deptName: null,
        warehouseName: null,
        distributionName: null,
        handleById: null,
        handleByName: null,
        status: null,
        returnTime: null,
        auditById: null,
        auditBy: null,
        auditRemark: null,
        returnRemark: null,
        createTime: null,
        updateTime: null,
        creator: null,
        updater: null,
        owner_name:null,
        order_time:null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.selectedOrderIds = [];
      this.open = true;
      this.title = "添加订单退货";
      this.form.sn = null;
    },
    // 获取供应商列表
    getSupplierList() {
      getSupplierList().then(response => {
        this.supplierList = response.data;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRefund(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改订单退货";
      });
    },
    handleGoodsSelectionChange(selection) {
      this.selectedGoods = selection;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 添加商品明细到表单数据
          if (this.returnList && this.returnList.length > 0) {
            this.form.returnGoodsList = this.returnList.map(item => ({
              goodsId: item.id,
              goodsSn: item.sn,
              goodsName: item.name,
              spec: item.spec,
              price: item.price,
              orderNum: item.num,
              returnNum: item.returnNum,
              amount: item.price * item.returnNum
            }));
          }

          if (this.form.id != null) {
            updateRefund(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRefund(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除订单退货编号为"' + ids + '"的数据项？').then(function() {
        return delRefund(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('xiaoshou/refund/export', {
        ...this.queryParams
      }, `refund_${new Date().getTime()}.xlsx`)
    },
    computed: {
      // 计算总金额
      totalAmount() {
        return this.orderGoodsList.reduce((sum, item) => {
          return sum + (item.amount || 0);
        }, 0);
      }
    }
  }
};
</script>
